package com.nogroup.springbootproject.controller;

import com.nogroup.springbootproject.dto.InfoDto;
import com.nogroup.springbootproject.entity.Info;
import com.nogroup.springbootproject.service.InfoService;
import com.nogroup.springbootproject.utils.PageUtils;
import com.nogroup.springbootproject.utils.result.DataResult;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Info)表控制层
 *
 * @author makejava
 * @since 2024-04-10 10:11:53
 */
@RestController
@RequestMapping("info")
public class InfoController {
    /**
     * 服务对象
     */
    @Resource
    private InfoService infoService;

    /**
     * 分页查询
     *
     * @param info 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Info>> queryByPage(Info info, PageRequest pageRequest) {
        return ResponseEntity.ok(this.infoService.queryByPage(info, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Info> queryById(@PathVariable("id") String id) {
        return ResponseEntity.ok(this.infoService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param info 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Info> add(Info info) {
        return ResponseEntity.ok(this.infoService.insert(info));
    }

    /**
     * 编辑数据
     *
     * @param info 实体
     * @return 编辑结果
     */
    @PutMapping
    @RequestMapping("edit")
    public DataResult edit(Info info) {
        return DataResult.successByData(this.infoService.update(info));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(String id) {
        return ResponseEntity.ok(this.infoService.deleteById(id));
    }

    @RequestMapping("getInfosByFuzzySearch")
    public DataResult getInfosByFuzzySearch(InfoDto infoDto){
        long count = infoService.countPage(infoDto);
        int index = PageUtils.getStartPage(infoDto.getPage(), infoDto.getLimit());
        System.out.println("studentDtoGetPage:" + infoDto.getPage() + "     studentDtoGetLimit:" + infoDto.getLimit());
        infoDto.setPage(index < count ? index : 0);
        System.out.println("studentDtoGetPage:" + infoDto.getPage() + "     studentDtoGetLimit:" + infoDto.getLimit());
        List<Info> infos = infoService.getInfosByFuzzySearch(infoDto);
        return DataResult.successByTotalData(infos,count);
    }

}

